﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Xml;
using DAL;
using System.Data.Linq;
using System.Xml.Linq;
using System.Data.SqlTypes;
using System.Data.SqlClient;

namespace Prototype1.AdminCompany
{
    public partial class WF_ExpenseChainConfig : System.Web.UI.Page
    {
        private PlaceHolder[] placeHolders;
        
        private const String TAG = "XPTO";
        private const String HIDDENFIELD_VALUE = TAG + "_buttonClicked";
        private const String HIDDENFIELD_LEVEL = TAG + "_levelClicked";
        private const String DYNAMICBUTTONSTAGPREFIX = "_DYNBUTTON_";
         
        protected override void OnPreLoad(EventArgs e)
        {
            base.OnPreLoad(e);
            if (Session["levels"] != null)
            {
                this.ChainTree.Controls.Clear();
                int x = (int)Session["levels"];
                placeHolders = new PlaceHolder[(int)Session["levels"]];                
            }

            ClientScript.RegisterHiddenField(HIDDENFIELD_LEVEL, "");
            ClientScript.RegisterHiddenField(HIDDENFIELD_VALUE, "");
        }     
              
        protected void Page_Load(object sender, EventArgs x)
        {
            if (!IsPostBack)
            {
                using (DataAccessDataContext dc = new DataAccessDataContext())
                {
                    //PROCEED LOADING LIST
                    var query = from dplevel in dc.DepartmentLevels
                                join dep in dc.Departments on dplevel.iddep equals dep.id
                                orderby dplevel.nivel
                                orderby dep.nome                                
                                select new{
                                    DepNome = dep.nome,
                                    DepLevelNome = dplevel.nome,
                                    DepLevelId = dplevel.idlevel,
                                    DepLevelLevel = dplevel.nivel
                                };



                    foreach (var e in query)
                        DepartamentList.Items.Add(new ListItem(e.DepNome+" - "+e.DepLevelNome+ " (Nível "+e.DepLevelLevel+")", e.DepLevelId.ToString()));
                }                
            }
            else
            {
                if (Request.Params[HIDDENFIELD_VALUE] != null)
                    if (Request.Params[HIDDENFIELD_VALUE].Length > 1)
                    {
                        String s = Request.Params[HIDDENFIELD_VALUE];
                        String w = Request.Params[HIDDENFIELD_LEVEL];

                        int level = int.Parse(w);

                        ListItem li = DepartamentList.Items.FindByValue(s);
                        if (li != null)
                        {
                            li.Enabled = true;
                            LinkedList<ListItem>[] tree = (LinkedList<ListItem>[])Session["tree"];
                            LinkedList<ListItem> list = tree[level - 1];
                            list.Remove(li);
                        }

                    }
            }           
        }

        protected void StartConfig(object sender, EventArgs e)
        {
            this.label1.Text = "Escolha um departamento e o nível da cadeia onde o quer inserir";
            this.nrLevels.Visible = false;
            this.Start.Visible = false;
            
            this.DepartamentList.Visible = true;
            this.ChainLevelOptions.Visible = true;
            this.AddDepButton.Visible = true;
            this.ChainTree.Visible = true;
            this.SaveTreeButton.Visible = true;

            int level = int.Parse(this.nrLevels.Text);
            this.levels.Value = "" + level;

            this.tb_ChainName.Visible = true;
            this.lb_ChainName.Visible = true;

            //init da tree em session
            LinkedList<ListItem>[] tree = new LinkedList<ListItem>[level];
                                     
                                   
            for (int i = 1; i <= level; ++i)
            {
                ChainLevelOptions.Items.Add(new ListItem(""+i,""+i));
                tree[i - 1] = new LinkedList<ListItem>();                
            }
            
            placeHolders = new PlaceHolder[level];

            Session.Add("tree", tree);
            Session.Add("levels", level);

        }

        private void InsertNewPlaceHolder(int i)
        {
            if (i > 0)
            {
                Label l = new Label();
                l.Text = "Nível " + i;

                PlaceHolder p = new PlaceHolder();                
                placeHolders[i-1] = p;         

                this.ChainTree.Controls.Add(l);
                this.ChainTree.Controls.Add(new LiteralControl("<br />"));
                this.ChainTree.Controls.Add(p);
                this.ChainTree.Controls.Add(new LiteralControl("<br />"));                
            }
        }

        

        protected void AddDep(object sender, EventArgs e)
        {
            if (this.DepartamentList.SelectedIndex > -1)
            {
                int level = int.Parse(this.ChainLevelOptions.SelectedItem.Value);

                LinkedList<ListItem>[] tree = (LinkedList<ListItem>[])Session["tree"];
                tree[level - 1].AddLast(this.DepartamentList.SelectedItem);

                DepartamentList.SelectedItem.Enabled = false;
                DepartamentList.SelectedItem.Selected = false;
            }
        }

        protected void SaveTree(object sender, EventArgs e)
        {
            if (Session["tree"] != null)
            {
                LinkedList<ListItem>[] tree = (LinkedList<ListItem>[])Session["tree"];
                /*
                 * Não gravar se algum nível vazio!!! 
                 * */
                for (int i = 0; i < tree.Length; ++i)
                    if (tree[i].Count == 0) return;
                

                XmlDocument xmldoc = new XmlDocument();
                
                /*
                <ExpenseChain id="xpto" version="1.0" maxLevel="2">
	                <Authorizer id="0" level="0"/>
	                <Authorizer id="1" level="0"/>
	                <Authorizer id="2" level="1"/>
	                <Authorizer id="2" level="2"/>	
                </ExpenseChain>
                */             
                

                XElement xml = new XElement("ExpenseChain");
                xml.SetAttributeValue("id",Guid.NewGuid().ToString());
                xml.SetAttributeValue("maxLevel",tree.Length);

                for (int i = 0; i < tree.Length; ++i)
                {
                    foreach (ListItem value in tree[i])
                    {

                        XElement x = new XElement("Authorizer");
                        x.SetAttributeValue("id",value.Value);
                        x.SetAttributeValue("level",i+1);
                        xml.Add(x);
                    }                    
                }                           


                Chain n;
                using(DataAccessDataContext dc = new DataAccessDataContext())
                {
                    n = new Chain();
                    n.id = Guid.NewGuid();
                    n.nome = tb_ChainName.Text;
                    n.date = DateTime.Now;
                    n.xml = xml;

                    dc.Chains.InsertOnSubmit(n);
                    dc.SubmitChanges();                    
                }
         
                Response.Redirect("~\\__AdminCompany\\WF_ExpenseChainViewer.aspx?expenseid="+n.id,true);
                Session.Remove("tree");
                Session.Remove("levels");

            }
        }                

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (IsPostBack)
            {
                if (Session["tree"] != null)
                {
                    LinkedList<ListItem>[] tree = (LinkedList<ListItem>[])Session["tree"];
                    for (int i = 0; i < tree.Length; ++i)
                    {
                        InsertNewPlaceHolder(i+1);
                        foreach (ListItem n in tree[i])
                            AddChainEntry(n.Text, i+1);
                    }                        
                }
            }
        }



        private void AddChainEntry(String n, int level)
        {
            
            Label l = new Label();
            l.Text = ""+n;

            Button b = new Button();
            b.Text = "Remove";
            b.ID = DYNAMICBUTTONSTAGPREFIX + l.Text;

            String value = "document.forms[0]." + HIDDENFIELD_VALUE + ".value='" + n + "';";
            String levl =  "document.forms[0]." + HIDDENFIELD_LEVEL + ".value='" + level + "';";
            
            b.Attributes.Add("onClick", value + levl + "document.forms[0].submit();");
            
            placeHolders[level-1].Controls.Add(l);
            placeHolders[level-1].Controls.Add(b);
            placeHolders[level-1].Controls.Add(new LiteralControl("<br />"));
        }


        
    }
}
